<?php
declare (strict_types = 1);

namespace app\model;

use think\Model;

/**
 * @mixin Model
 */
class Config extends Model
{
    public static array $list = [
        'default_pid'=> ['注册默认上级ID','1'],
        'v1_ratio'=> ['VIP1分佣比例(%)','15'],
        'v2_ratio'=> ['VIP2分佣比例(%)','15'],
        'v3_ratio'=> ['VIP3分佣比例(%)','15'],
    ];

    const CACHE_KEY = 'db_config_data';

    public function get($key='') {
        static $config;
        if (!isset($config) || ($key && !isset($config[$key]))) {
            $config = cache(self::CACHE_KEY);
            if (!$config || input('refresh_config') || ($key && !isset($config[$key]))) {
                $configDb = new Config();
                $ret = $configDb->field('key,value')->column('value', 'key');
                $config = [];
                foreach (self::$list as $k => $val) {
                    $config[$k] = $ret[$k]['value'] ?? $val[1];
                }
                cache(self::CACHE_KEY, $config, 86400*7);
            }
        }
        if ($key) {
            return $config[$key] ?? '';
        }
        return $config;
    }

    public function refreshCache() {
        cache('db_config_data', null);
    }
}
